package com.ald.crossex.system.wechat;

import com.ald.crossex.dto.wechat.WechatBaseAccessTokenResponse;
import com.ald.crossex.system.SystemCache;
import com.ald.crossex.system.SystemConfig;
import com.alibaba.fastjson.JSON;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.log4j.Logger;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * Created by lishijiong on 15/2/12.
 *  access_token  公众号的全局唯一票据
 */
public class RefreshAccessTokenJob {


    private static final Logger logger = Logger.getLogger(RefreshAccessTokenJob.class);


    public void execute() {


        String requestUrl = SystemConfig.getVal("access_token_url") + "?grant_type=client_credential"
                + "&appid=" + SystemConfig.getVal("wechat_mp_AppID")
                + "&secret=" + SystemConfig.getVal("wechat_mp_AppSecret");
        try {
            HttpClient client = new DefaultHttpClient();
            HttpGet get = new HttpGet(requestUrl);
            HttpResponse response = client.execute(get);
            if (response.getStatusLine().getStatusCode() == 200) {
                String jsonResult = getResponseString(response, "UTF-8");

                WechatBaseAccessTokenResponse token = JSON.parseObject(jsonResult, WechatBaseAccessTokenResponse.class);
                if (token.getErrcode() == null) {
                    SystemCache.put("access_token", token.getAccess_token());
                    logger.info("刷新微信 access_token 成功");
                }

            } else {
                logger.error("刷新微信 access_token 失败");
            }
        } catch (Exception e) {
            logger.error("刷新微信 access_token 失败"+e.getMessage());
        }


    }

    private static String getResponseString(HttpResponse response, String charset)
            throws IOException {
        InputStream inputStream = response.getEntity().getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                inputStream, charset));
        StringBuffer buffer = new StringBuffer();
        String line = "";
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }
        return buffer.toString();
    }
}
